package com.report.controller;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.dev33.satoken.SaManager;
import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.URLUtil;
import cn.hutool.extra.qrcode.QrCodeUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import com.report.constants.TagConstants;
import com.report.dto.request.*;
import com.report.dto.response.*;
import com.report.dto.response.zu.ReportItemRes;
import com.report.entity.Partner;
import com.report.entity.Poster;
import com.report.entity.ResearchFile;
import com.report.entity.Tag;
import com.report.service.*;
import com.report.utils.FileUtils;
import com.zmh.framework.annotation.LogAnnotation;
import com.zmh.framework.oss.OssConfigure;
import com.zmh.framework.properties.SmsProperties;
import com.zmh.framework.redis.RedisCache;
import com.zmh.framework.sms.AliSms;
import com.zmh.framework.sys.dto.request.common.PageResponseDTO;
import com.zmh.framework.util.QrCode;
import com.zmh.framework.util.Result;
import javafx.scene.control.Tab;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.*;
import java.net.URL;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author summer
 * @date 2024-06-27 21:16
 */
@RestController
@RequestMapping(value = "/web")
@Slf4j
@AllArgsConstructor
public class WebController {

    private final ITagService tagService;

    /**
     * 只查询24小时的热搜数据
     * @return
     */
    @GetMapping(value = "/searchList")
    public Result<List<TagRes>> searchList(){
        return Result.successResult(tagService.searchList(1,15,1));
    }

    private final RedisCache redisCache;

    /**
     * 近期热点
     * @return
     */
    @PostMapping(value = "/hotSpotList")
    public Result<Page<TagRes>>  hotSpotList(@RequestBody PageResponseDTO pageResponseDTO){
        return Result.successResult(tagService.hotSpotList(pageResponseDTO.getPageNum(),pageResponseDTO.getPageSize(),1));
    }


    //研报类型
    @GetMapping(value = "/recentTagList")
    public Result<List<TagRes>> recentTagList(){
        List<Tag> list = tagService.list(Wrappers.lambdaQuery(Tag.class).eq(Tag::getMark, 4));
        return Result.successResult(Convert.toList(TagRes.class, list));
    }

    /**
     * 主要行业
     * @return
     */
    @GetMapping(value = "/AllIndustryList")
    public Result<List<TagRes>>  industryList(){
        LambdaQueryWrapper<Tag> eq = Wrappers.lambdaQuery(Tag.class).eq(Tag::getMark, 2);
       List<Tag> list = tagService.list(eq);
        return Result.successResult(Convert.toList(TagRes.class, list));
    }

    @PostMapping(value = "/industryPage")
    public Result<Page<TagRes>>  industryList(@RequestBody PageResponseDTO pageResponseDTO){
        return Result.successResult(tagService.hotSpotList(pageResponseDTO.getPageNum(),pageResponseDTO.getPageSize(),2));
    }



    private final IReportService reportService;

    /**
     * 今日推荐
     * @return
     */
    @GetMapping(value = "/todayRecommendList")
    public Result<List<TodaySellRes>> todayRecommendList(){
        List<TodaySellRes> lists=reportService.todayRecommendList();
        return Result.successResult(lists);
    }

    /**
     * 今日推荐
     * @return
     */
    @GetMapping(value = "/rankingList")
    public Result<List<TodaySellRes>>rankingList(){
        List<TodaySellRes> lists=reportService.rankingList();
        return Result.successResult(lists);
    }


    /**
     * 研报类型、招股书、财报
     * @return
     */
    @PostMapping(value = "/recentList")
    public Result<Page<ReportRes>> recentList(@RequestBody ReportReq recentReq){
        Page<ReportRes> lists=reportService.lists(recentReq);
        return Result.successResult(lists);
    }

    private final IReportFileService reportFileService;

    /**
     * 首页查询专题列表
     * @param pageNum
     * @param pageSize
     * @return
     */
    @PostMapping(value = "/specialList")
    public Result<Page<SpecialRes>> specialList(@RequestBody ReportReq specialReq){
        Page<SpecialRes> specialResList=reportFileService.specialList(specialReq.getPageNum(),specialReq.getPageSize());
        return Result.successResult(specialResList);
    }

    private final PartnerService partnerService;

    /**
     * 合作伙伴
     * @return
     */
    @GetMapping(value = "/partnerList")
    public Result<List<PartnerRes>> partnerList(){
        List<Partner> list = partnerService.list();
        return Result.successResult(Convert.toList(PartnerRes.class,list));
    }

    private final PosterService posterService;

    /**
     * 广告位
     * @return
     */

    @GetMapping(value = "/posterList")
    public Result<List<PosterRes>> posterList(){
        List<Poster> list = posterService.list(Wrappers.lambdaQuery(Poster.class).orderByDesc(Poster::getCreateTime));
        return Result.successResult(Convert.toList(PosterRes.class,list));
    }


    private final IMemberService memberService;

   private final InsightService insightService;
    @PostMapping(value = "/insightList")
    public Result<Page<InsightRes>> insightList(@RequestBody InsightReq insightReq){
        Page<InsightRes> page= insightService.insightList(insightReq);
        return Result.successResult(page);
    }


    /**
     * 手机号登录
     * @param phone
     * @param code
     * @return
     */
    @PostMapping(value = "/login")
    @LogAnnotation(msg = "PC")
    public Result<SaTokenInfo>  login(@RequestBody WebLoginRes webLoginRes){
        MemberRes memberRes=memberService.login(webLoginRes.getPhone(),webLoginRes.getPassword());
        StpUtil.login(memberRes.getId(),"web");
        SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
        if(StrUtil.isNotEmpty(SaManager.getConfig().getTokenPrefix())){
            tokenInfo.setTokenValue(SaManager.getConfig().getTokenPrefix()+" "+tokenInfo.getTokenValue());
        }
        return Result.successResult(tokenInfo);
    }


    private final ReportImageService reportImageService;


    /**
     * 图像
     * @param fileReq
     * @return
     */
    @PostMapping(value = "/imageLists")
    public Result<Page<WebReportImageRes>> imageLists(@RequestBody ReportImageReq reportImageReq){

        return  Result.successResult(reportImageService.imageLists(reportImageReq));
    }


    private final ReportItemService reportItemService;

   @PostMapping(value = "/reportList")
    public Result<Page<ReportItemRes>> lists(@RequestBody ReportItemReq reportReq) {

        return Result.successResult(reportItemService.findReportList(reportReq));
    }


  @PostMapping(value = "/pdfLists")
  public Result<Page<ReportItemRes>> pdfLists(@RequestBody ReportItemReq reportReq) {

       return Result.successResult(reportItemService.pdfLists(reportReq));
  }

    private final IFileService fileService;


    @GetMapping(value = "/filePath/{fileId}")
  public Result<String> filePath(@PathVariable Integer fileId){
        ResearchFile researchFile = fileService.getById(fileId);
        return Result.successResult(researchFile.getUrl());
  }

    private final AliSms aliSms;


    /**
     * 短信验证码
     * @param sendPhoneReq
     * @return
     */
    @PostMapping(value = "/sendCode")
    public Result<String> sendCode(@Valid @RequestBody WebSendPhoneReq sendPhoneReq){
        aliSms.sendSms(sendPhoneReq.getPhone());
        return Result.successResult();
    }


    //editUserPassword  registerUser

    @PostMapping(value = "/registerUser")
    public Result<String> registerUser(@Valid @RequestBody SendPhoneReq sendPhoneReq){
        memberService.registerUser(sendPhoneReq);
        return Result.successResult();
    }

    @PostMapping(value = "/editUserPassword")
    public Result<String> editUserPassword(@Valid @RequestBody SendPhoneReq sendPhoneRe){
        memberService.editUserPassword(sendPhoneRe);
        return Result.successResult();
    }


    @PostMapping(value = "/uploadPdf")
    public Result<String> uploadPdf(MultipartFile file){
        memberService.uploadPdf(file);
        return Result.successResult();
    }

    private final IBrowseService browseService;

    /**
     * 判断阅读数量
     * @return
     */
    @GetMapping(value = "/memberReadNum")
    public Result<String> memberReadNum(HttpServletRequest request){
        if(StpUtil.isLogin()){
            browseService.readNum();
        }else {
            browseService.isReadNum(request);
        }
        return Result.successResult();
    }


     /**
     * 今日阅读数量
     * @param memberId
     * @return
     */
    @PostMapping(value = "/readDayNum")
    public Result<String> readDayNum(@RequestBody BrowseReq browseReq){
        browseService.readDayNum(browseReq);
        return Result.successResult();
    }

    private final WxMaService wxMaService;

    //WxMaService
    @GetMapping(value = "/getMiniCode/{id}")
    public Result<String> getMiniCode(@PathVariable Integer id) throws WxErrorException {
        File qrcode = wxMaService.getQrcodeService().createQrcode("/pages/report/pdf/pdf?id=" + id);

        return Result.successResult("data:image/png;base64,"+FileUtils.fileToBase64(qrcode));
    }

    private final OssConfigure ossConfigure;

    @PostMapping(value = "/uploadAvatar")
    public Result<String> uploadAvatar(MultipartFile file){
        log.info("file:{}",file);
        String s = ossConfigure.uploadFile(file);
        return Result.successResult(ossConfigure.getAccessUrl()+s);
    }


    private final DownloadReportService downloadReportService;

    @GetMapping(value = "/downloadReport")
    public Result<String> downloadReportRole(){
        downloadReportService.findMemberDownloadReportFile();
        return Result.successResult();
    }


}
